package br.com.wss.recursos;

import java.io.IOException;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.helper.StringUtil;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.nodes.Node;
import org.jsoup.nodes.TextNode;
import org.jsoup.select.Elements;
import org.jsoup.select.NodeTraversor;
import org.jsoup.select.NodeVisitor;

/**
 * 
 * @author Wenner Santos Feito em 15/05/2012 as 21:33:46
 */
public class HtmlToPlainText {

	private String url;
	private Element element;

	public HtmlToPlainText(String url) {
		this.url = url;
	}

	public String getText(String idTag) {
		Connection connection = null;
		Document doc = null;
		try {
			connection = Jsoup.connect(url);
			doc = connection.get();
		} catch (IOException ex) {
			return null;
		}
		element = doc.getElementById(idTag);
		return getPlainText(doc.getElementById(idTag));
	}

	public String getTextSumario() {
		Elements elements = element.getElementsByTag("table");
		return getPlainText(elements.get(0));
	}

	/**
	 * Format an Element to plain-text
	 * 
	 * @param element
	 *            the root element to format
	 * @return formatted text
	 */
	public String getPlainText(Element element) {
		FormattingVisitor formatter = new FormattingVisitor();
		NodeTraversor traversor = new NodeTraversor(formatter);
		traversor.traverse(element); // walk the DOM, and call .head() and
										// .tail() for each node

		return formatter.toString().trim();
	}

	// the formatting rules, implemented in a breadth-first DOM travarse
	private class FormattingVisitor implements NodeVisitor {
		private StringBuilder accum = new StringBuilder(); // holds the
															// accumulated text

		// hit when the node is first seen
		public void head(Node node, int depth) {
			String name = node.nodeName();
			if (node instanceof TextNode) {
				String txt = ((TextNode) node).text().trim();
				if (txt.length() > 1) {
					append(txt + "\n"); // TextNodes carry all user-readable
										// text in the DOM.
				}
			} else if (name.equals("li")) {
				append("* ");
			}
		}

		// hit when all of the node's children (if any) have been visited
		public void tail(Node node, int depth) {
			/**
			 * String name = node.nodeName(); if (name.equals("br")) {
			 * append("\n"); } else if (StringUtil.in(name, "p", "h1", "h2",
			 * "h3", "h4", "h5")) { append("\n"); }
			 */
		}

		// appends text to the string builder with a simple word wrap method

		private void append(String text) {
			if (text.equals("\\s+")
					&& (accum.length() == 0 || StringUtil.in(
							accum.substring(accum.length() - 1), " ", "\n"))) {
				return; // don't accumulate long runs of empty spaces
			}

			accum.append(text);
		}

		public String toString() {
			return accum.toString();
		}
	}
}
